package com.spark.concurrency.other;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多个线程互相等待，直到到达同一个同步点，再继续一起执行。
 */
public class CyclicBarrierTest implements Runnable {

    //创建拦截线程数为4，线程都到达barrier后，执行当前类的run方法，
    private final CyclicBarrier cyclicBarrier = new CyclicBarrier(4, this);

    //创建只能启动4个线程的线程池，
    private final Executor executor = Executors.newFixedThreadPool(4);

    //保存每个线程的计算结果，
    private final ConcurrentHashMap<String, Integer> count = new ConcurrentHashMap<>();

    @Override
    public void run() {
        AtomicInteger result = new AtomicInteger();
        count.forEach((k, v) -> result.addAndGet(v));
        System.out.println(Thread.currentThread().getName() + "_result" + result.get());
    }

    public void calculate() {
        for (int i = 0; i < 4; i++) {
            executor.execute(() -> {
                String threadName = Thread.currentThread().getName();
                count.put(threadName, 10);
                try {
                    System.out.println(threadName + " is waiting，");
                    cyclicBarrier.await();
                    System.out.println(threadName + " is working，");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public static void main(String[] args) {
        new CyclicBarrierTest().calculate();
    }

}
